import { ConfigService } from '../../../../core/common/config.service';
import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { Http } from '@angular/http';
import { TranslateService } from '@ngx-translate/core';
import { ECharts } from 'echarts-ng2';
import { flyIn } from '../../../animations/fly-in';
import { PortalService } from '../service/portal.service';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-userportal',
  templateUrl: './userportal.component.html',
  styleUrls: ['./userportal.component.scss'],
  animations: [flyIn]
})
export class UserPortalComponent implements OnInit, OnDestroy {
  @ViewChild('weekBandwidthRank') weekBandwidthRank: ECharts;
  public destroy = false;
  public wholenetBwData = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}bps ({d}%)',
      position: ['50%', '50%']
    },
    series: [
      {
        name: '应用来源',
        type: 'pie',
        radius: ['40%', '55%'],
        data: []
      }
    ],
  };
  public nodestatistics = [
    {
      'up': 0,
      'category': 'Reachability Status',
      'down': 0,
      'categoryName': '设备状态'
    },
    {
      'up': 0,
      'category': 'Service Status',
      'down': 0,
      'categoryName': '服务状态'
    },
    {
      'up': 0,
      'category': 'Interfaces',
      'down': 0,
      'categoryName': '接口状态'
    },
    {
      'up': 0,
      'category': 'Paths',
      'down': 0,
      'categoryName': '连接路径状态'
    }
  ];
  public nodesdetail: any;
  public nodeBwData: any;
  public switch = '1';
  public checkStatus: any;
  public custId: any;
  /****************************************************************************/
  @ViewChild('Bmap') BMap;
  // public wuhan_interface_on: Observable<any>;
  public opts = {
    markers: [],
    // 地图初始位置
    center: {
      longitude: 102,
      latitude: 34
    },
    zoom: 5,
    // 缩放地图的控件
    navCtrl: false,
    // 右下角地图缩略图
    overviewCtrl: false
  };
  public offlineOpts = {
    retryInterval: 5000,
    txt: 'NO-NETWORK'
  };
  public nodesSelect: any = {
    id: '-1',
    nodeItems: [
      { id: '-1', text: '全部节点' },
      { id: '0', text: '正常节点' },
      { id: '1', text: '异常节点' }
    ]
  };
  /****************************************************************************/
  constructor(public configService: ConfigService, public http: Http, private translate: TranslateService,
    public portalService: PortalService, private route: ActivatedRoute, private router: Router) { }
  ngOnInit() {
    $(window).resize(() => {
      if (!this.destroy) {
        this.weekBandwidthRank.resize();
      }
    });
    this.nodeStatistics();
    this.wholenetBwRank();
    this.nodeBwRank();
  }
  ngOnDestroy() { }
  public nodeStatistics(): void {
    this.portalService.getMarkers().map(res => {
      return res.data;
    }).subscribe((res: any) => {
      // console.log(res.data);
      const branchHealth = res.data;
      for (let i = 0; i < branchHealth.length; i++) {
        if (branchHealth[i].reachable === 'REACHABLE') {
          ++this.nodestatistics[0].up;
        } else {
          ++this.nodestatistics[0].down;
        }
        if (branchHealth[i].servicestatus === 'GOOD') {
          ++this.nodestatistics[1].up;
        } else {
          ++this.nodestatistics[1].down;
        }
        this.nodestatistics[2].up += branchHealth[i].interfaceup;
        this.nodestatistics[2].down += branchHealth[i].interfacedown;
        this.nodestatistics[3].up += branchHealth[i].pathup;
        this.nodestatistics[3].down += branchHealth[i].pathdown;
      }
    });
  }
  public statusDetail(val) {
    // console.log(val);
    switch (val) {
      case 'Reachability Status': this.checkStatus = '设备可达状态';
        break;
      case 'Service Status': this.checkStatus = '服务状态';
        break;
      case 'Interfaces': this.checkStatus = '接口状态';
        break;
      case 'Paths': this.checkStatus = '连接路径状态';
        break;
    }
    this.portalService.statusDetail(val).map(res => {
      return res.data;
    }).subscribe((res: any) => {
      // console.log(res.data);
      if (res.data instanceof Array) {
        this.switch = '2';
        this.nodesdetail = res.data;
      } else {
        this.switch = '3';
        this.nodesdetail = res.data['versanms.VTable'].rows;
        // console.log(this.nodesdetail);
      }
    });
  }
  public return() {
    this.switch = '1';
  }
  public wholenetBwRank() {
    this.portalService.wholenetBwRank().map(res => {
      return res.data;
    }).subscribe((res: any) => {
      // console.log(res);
      const series = [];
      let sum = 0;
      const allBandwidth = res.data;
      const allBandwidthChange = allBandwidth.sort(this.compare('totalbandwidth'));
      const front = allBandwidthChange.slice(0, 5);
      const after = allBandwidthChange.slice(5);
      front.forEach(function(item, i) {
        series.push({
          'name': item.application,
          'value': item.totalbandwidth
        });
      });
      for (let i = 0; i < after.length; i++) {
        sum += after[i].totalbandwidth;
      }
      series.push({
        'name': 'others',
        'value': sum
      });
      this.wholenetBwData.series[0].data = series;
      this.weekBandwidthRank.setOption(this.wholenetBwData);
    });
  }
  public compare(property) {
    return function(obj1, obj2) {
      const value1 = obj1[property];
      const value2 = obj2[property];
      return value2 - value1;
    };
  }
  public nodeBwRank() {
    this.portalService.nodeBwRank().map(res => {
      return res.data;
    }).subscribe((res: any) => {
      const series = res.data.sort(this.compare('bandwidth'))
      if (res.data.length > 5) {
        this.nodeBwData = series.slice(0, 5);
      } else {
        this.nodeBwData = series;
      }
      this.custId = res.custId;
    });
  }
  /****************************************************************************/
  public loadMap(map: any) {
    // console.log('map instance here', map);
    this.getMarkers();
  }
  public clickmap(e: any) {
    // console.log(`Map clicked with coordinate: ${e.point.lng}, ${e.point.lat}`);
    this.BMap.clearLinks();
  }
  public markersSelect(event) {
    this.BMap.displayMarkers(Number(event));
  }
  // 获取所有节点
  public getMarkers() {
    const okIcon = 'assets/img/map/blue.png';
    const badIcon = 'assets/img/map/red.png';
    this.portalService.getMarkers().map(res => {
      // console.log(JSON.stringify(res));
      return res.data;
    }).subscribe((res: any) => {
      if (res.code == '0') {
        // console.log(res);
        res.data.forEach((item) => {
          if (item.status === 0) {
            item.icon = okIcon;
          } else {
            item.icon = badIcon;
          }
          item.width = item.height = 20;
          item.enableDragging = false;
        });
        this.opts.markers = res.data;
        this.BMap.updataMapInfo();
        // console.log(this.opts.markers);
      } else {
        console.log('获取坐标点失败');
      }
    });
  }
  // 节点点击事件getNodesLink()
  public clickMarker(marker: any) {
    // console.log(marker.devname);
    const beginPoint: any = {
      longitude: marker.point.lng,
      latitude: marker.point.lat
    };
    this.portalService.getNodesLink(marker.devname).map(res => {
      // console.log(JSON.stringify(res));
      return res.data;
    }).subscribe((res: any) => {
      let showLines: any;
      if (res.code == '0') {
        const msg = `<p style="font-size:1.1em; padding-left:10px; color:#0398C9">节点名：${res.bandwidth[0].nodeName}</p>
                                     <p style="padding-left:10px;color:#666">上行带宽 ： ${res.bandwidth[0].bwTx} bps</p>
                                     <p style="padding-left:10px;color:#666">下行带宽 ： ${res.bandwidth[0].bwRx} bps</p>
                                    `;
        this.BMap.showInfo(marker, msg);
        if (this.nodesSelect.id === '-1') {
          showLines = res.data;
        } else {
          showLines = res.data.filter((item) => {
            return item.status === Number(this.nodesSelect.id);
          });
        }
        this.BMap.displayLinks(beginPoint, showLines);
      } else {
        console.log('获取链路信息失败');
      }
    });
  }
  viewDetail(node): void {
    const params: any = {};
    params.data = JSON.stringify(node);
    params.custId = this.custId;
    params.fromUserPortal = true;
    this.router.navigate(['/userinfo/brandRank', params], { relativeTo: this.route.parent, skipLocationChange: true });
  }
}
